package cn.ha.cz.springboot.interceptor.upload;

import java.text.NumberFormat;

import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.ProgressListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * SpringBoot MultipartFile 监控上传文件进度
 * <br>
 * https://blog.csdn.net/weixin_37264997/article/details/82622897
 * @author Administrator
 *
 */
@Component
public class FileUploadProgressListener implements ProgressListener {
	Logger logger = LoggerFactory.getLogger(this.getClass());
	private HttpSession session;

	public void setSession(HttpSession session) {
		this.session = session;
		logger.info("upload_percent 0--------------------------------------");
		session.setAttribute("upload_percent", 0);
	}

	@Override
	public void update(long bytesRead, long contentLength, int items) {
		//将数据进行格式化
        //已读取数据由字节转换为M
        double readM=bytesRead/1024.0/1024.0;
        //已读取数据由字节转换为M
        double totalM=contentLength/1024.0/1024.0;
        //已读取百分百
        double percent=readM/totalM;
        
        //格式化数据
        //已读取
        String readf=dataFormat(bytesRead);
        //总大小
        String totalf=dataFormat(contentLength);
        //进度百分百
        NumberFormat format=NumberFormat.getPercentInstance();
        String progress=format.format(percent);
        
        //将信息存入session
        session.setAttribute("upload_percent", percent);
//        session.setAttribute("upload_percent2", percent);
        
        //打印消息到控制台
        System.out.println("percent===>"+percent);
//        System.out.println("pBytesRead===>"+bytesRead);
//        System.out.println("pContentLength==>"+contentLength);
//        System.out.println("pItems===>"+items);
//        System.out.println("readf--->"+readf);
//        System.out.println("totalf--->"+totalf);
//        System.out.println("progress--->"+progress);
	}
	
	
	/**
     * 格式化读取数据的显示
     * @param data要格式化的数据 单位byte
     * @return 格式化后的数据，如果小于1M显示单位为KB，如果大于1M显示单位为M
     */
    public String dataFormat(double data){
        String formdata="";
        if (data>=1024*1024) {//大于等于1M
            formdata=Double.toString(data/1024/1024)+"M";
        }else if(data>=1024){//大于等于1KB
            formdata=Double.toString(data/1024)+"KB";
        }else{//小于1KB
            formdata=Double.toString(data)+"byte";
        }
        return formdata.substring(0, formdata.indexOf(".")+2);
    }
}
